package com.cipe.cmrs.util;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;

import com.cipe.cmrs.model.BaseEntity;

public class BaseEntityCollectionEditor extends CustomCollectionEditor {

	protected Logger logger = LoggerFactory.getLogger(BaseEntityCollectionEditor.class); 

	private final Map<String, BaseEntity> entityCache;

    @SuppressWarnings("rawtypes")
	public BaseEntityCollectionEditor(Class collectionType, Collection<? extends BaseEntity> entityCollection) {
		super(collectionType);

		entityCache = new HashMap<String, BaseEntity>();
		for (BaseEntity entity : entityCollection) {
			entityCache.put(entity.getId().toString(), entity);
		}
	}

	@Override
    protected Object convertElement(Object element) {
		try {
			BaseEntity entity = null;

	        if (element instanceof BaseEntity) {
	        	entity = (BaseEntity) element;

	        } else if (element instanceof String) {
	            //From the JSP 'element' will be a String
	        	if (!StringUtils.isBlank(element.toString())) {
	            	entity = entityCache.get(element.toString());
	        	}

	        } else if (element instanceof Serializable) {
	            //From the database 'element' will be a Serializable
	        	entity = entityCache.get(element.toString());
	        }

	        return entity;
        } catch (Exception ex) {
			logger.debug("Value could not be converted: " + (String) element);
			throw new IllegalArgumentException("Value could not be converted: " + (String) element);
        }
    }
}
